package org.xbl.xchain.sdk.tx;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.xbl.xchain.sdk.SysConfig;
import org.xbl.xchain.sdk.module.auth.types.Token;
import org.xbl.xchain.sdk.types.Fee;
import org.xbl.xchain.sdk.types.MsgTypeValue;
import org.xbl.xchain.sdk.types.TxConfig;
import org.xbl.xchain.sdk.utils.EncodeUtils;

import java.util.List;

@Data
public class StdSignBytesV1 {

    @JSONField(name = "account_number")
    private Long accNum;
    @JSONField(name = "chain_id")
    private String chainId;
    private Fee fee;
    private String memo;
    private MsgTypeValue[] msgs;
    private Long sequence;

    public StdSignBytesV1(Long accNum, Long sequence, String chainId, List<MsgTypeValue> msgs, TxConfig txConfig) {
        this.accNum = accNum;
        this.sequence = sequence;
        this.chainId = chainId;
        if (SysConfig.hasFee) {
            Fee fee = new Fee();
            fee.setAmount(new Token[]{});
            fee.setGas(txConfig.getGas());
            this.fee = fee;
        }
        this.memo = txConfig.getMemo();
        this.msgs = msgs.toArray(new MsgTypeValue[]{});
    }

    public StdSignBytesV1(Long accNum, Long sequence, String chainId, List<MsgTypeValue> msgs, Fee fee, String memo) {
        this.accNum = accNum;
        this.sequence = sequence;
        this.chainId = chainId;
        if (SysConfig.hasFee) {
            this.fee = fee;
        }
        this.memo = memo;
        this.msgs = msgs.toArray(new MsgTypeValue[]{});
    }


    @Override
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
                .append("account_number", accNum)
                .append("chain_id", chainId)
                .append("fee", fee)
                .append("memo", memo)
                .append("msgs", msgs)
                .append("sequence", sequence)
                .toString();
    }

    public String toJson() throws JsonProcessingException {
        return EncodeUtils.toJsonStringSortKeys(this);
    }
}
